package com.scedu.service.impl;


import com.scedu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CustomUserDetailServiceImpl implements UserDetailsService {
    //根据 账号查询用户信息
    @Autowired
     private UserService userService;
    @Autowired
    PasswordEncoder passwordEncoder; //加密规则
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.连接数据库查询用户基本信息
        com.scedu.entity.User loginuser=userService.findByUserName(username); //根据用户名查找用户
        if (loginuser==null) {
            //return  null;
            throw new UsernameNotFoundException("not found"); //没有用户，抛出错误
        }
        log.info("用户信息={}",loginuser);
        //2、根据用户的id查询用户的权限
        List<String> permissions=userService.findPermissionByUid(loginuser.getId());
        log.info("权限有：{}",permissions );
        //将permisions转为数组
        String[] permissionArray=new String[permissions.size()];
        permissions.toArray(permissionArray);

        UserDetails userDetails= User
                .withUsername(loginuser.getUsername()) //构造用户的用户名 密码 权限
                .password(loginuser.getPassword()) //数据库取出的是加密后的密码
                .authorities(permissionArray) //授权 给与权限
                //.roles(permissionArray) //授权 给与角色
                .build();
        log.info("userDetails={}",userDetails);
        return userDetails;
    }


}
